package cn.hd01.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.hd01.repository.IntegrationRuleRepository;
import cn.hd01.repository.entity.IntegrationRule;
import cn.hd01.service.IntegrationRuleService;

@Service
public class IntegrationRuleServiceImpl extends BaseServiceImpl<IntegrationRule, Integer> implements IntegrationRuleService {

	private IntegrationRuleRepository repository;
	
	@Autowired
	public IntegrationRuleServiceImpl(IntegrationRuleRepository repository) {
		super(repository);
		this.repository = repository;
	}

	@Override
	public Page<IntegrationRule> findAll(final IntegrationRule ir, Pageable pageable) {
		if (ir == null) {
			return repository.findAll(pageable);
		}

		return repository.findAll(Specifications.where(new Specification<IntegrationRule>() {
			@Override
			public Predicate toPredicate(Root<IntegrationRule> r, CriteriaQuery<?> q, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<Predicate>();
				
				if (StringUtils.hasText(ir.getRuleName())) {
					predicates.add(cb.like(r.get("ruleName").as(String.class), "%" + ir.getRuleName() + "%"));
				}
				
				return cb.and(predicates.toArray(new Predicate[] {}));
			}
		}), pageable);
		
	}
	
}
